﻿using Liju.Model;
using LiJu.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LiJu
{
    public partial class ParameterManager2 : Form
    {
        public static List<ScrewParam> ScrewParams = new List<ScrewParam>();
        public  List<ScrewParam> ReadScrewParams = new List<ScrewParam>();
        /// <summary>
        /// 记录表格默认字体
        /// </summary>
        private Font defaultFont = new Font("Microsoft YaHei", 9);
        private Image torqueParmImg = Properties.Resources.parameterSet1;
        private Image torqueLimtParmImg = Properties.Resources.parameterSet2;
        private Image speedParmImg = Properties.Resources.parameterSet3;
        public ParameterManager2()
        {
            InitializeComponent();
            DDKBatch.ScrewParamReturnAction += AddScrewParameters;
            InitGridView();
            InitImageNavigation();
        }
        private void ParameterManager2_Load(object sender, EventArgs e)
        {
            try
            {
                //if (!DDKBatch.isMonitor)
                //{
                //    DDKBatch.Connection("192.168.11.10", 23);
                //}
                LoadParameterData();

            }
            catch (Exception ex)
            {
               Debug.WriteLine($"DDK电批连接失败->{ex.Message}");
            }

        }

        #region Methods
        /// <summary>
        /// 初始化表格数据
        /// </summary>
        private void InitGridView()
        {
            parameterNumGridView.AllowUserToAddRows = false;
            parameterDataGridView.AllowUserToDeleteRows = false;

            parameterNumGridView.CellBeginEdit += ParameterNumGridView_CellBeginEdit;
            parameterNumGridView.CellEndEdit += ParameterNumGridView_CellEndEdit;
            parameterDataGridView.CellBeginEdit += ParameterDataGridView_CellBeginEdit;
            parameterDataGridView.CellEndEdit += ParameterDataGridView_CellEndEdit;

            //列标题居中
            parameterNumGridView.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //单元格字体居中显示
            parameterNumGridView.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            // 设置选中单元格的背景颜色
            parameterNumGridView.DefaultCellStyle.SelectionBackColor = System.Drawing.ColorTranslator.FromHtml("#BFEFFF");
            //设置选择模式为整行选择
            parameterNumGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            // 设置选中单元格的前景颜色
            parameterNumGridView.DefaultCellStyle.SelectionForeColor = Color.Black;
            //this.parameterNumGridView.DefaultCellStyle.Font = defaultFont;

            // 设置选择模式
            parameterNumGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            parameterNumGridView.MultiSelect = false;

            //// 取消默认选中
            //parameterNumGridView.ClearSelection();

            ////列标题居中
            //parameterDataGridView.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            ////单元格字体居中显示
            //parameterDataGridView.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            // 设置选中单元格的背景颜色
            parameterDataGridView.DefaultCellStyle.SelectionBackColor = System.Drawing.ColorTranslator.FromHtml("#BFEFFF");
            //设置选择模式为整行选择
            //parameterDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            // 设置选中单元格的前景颜色
            parameterDataGridView.DefaultCellStyle.SelectionForeColor = Color.Black;
            //this.parameterDataGridView.DefaultCellStyle.Font = defaultFont;
            // 创建一个新的Font对象
            Font columnFont = new Font("Microsoft YaHei", 10, FontStyle.Bold);
            // 设置列头的默认单元格样式
            parameterNumGridView.ColumnHeadersDefaultCellStyle.Font = columnFont;
            parameterDataGridView.ColumnHeadersDefaultCellStyle.Font = columnFont;

        }
        /// <summary>
        /// 任务吗修改后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ParameterNumGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            string newName = parameterNumGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString();
            if (e.ColumnIndex ==1)
            {
                if (string.IsNullOrEmpty(newName))
                {
                    MessageBox.Show("请输入参数名");
                    parameterNumGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = oldvalue;
                }
                else
                {
                    int index = (int)parameterNumGridView.Rows[e.RowIndex].Cells["ParamIndexColumn"].Value;
                    var param = ScrewParams.Find(o => o.taskId == index);
                    if (param != null)
                    {
                        param.name = newName;
                    }
                    parameterNumGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = newName;
                }
            }
        }

        string oldName = null;
        /// <summary>
        /// 任务名修改前
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ParameterNumGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.RowIndex == -1)
            {
                return;
            }
            oldName = parameterNumGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString();
        }

        /// <summary>
        /// 初始化图片导航
        /// </summary>
        private void InitImageNavigation()
        {
            pic_TorqueParams.Image = GetThumbnail(torqueParmImg, 50, 50);
            pic_TorqueParams.Click += Pic_TorqueParams_Click; 
            pic_TorqueRange.Image = GetThumbnail(torqueLimtParmImg, 50, 50);
            pic_TorqueRange.Click += Pic_TorqueRange_Click;
            pic_AngleSpeed.Image = GetThumbnail(speedParmImg, 50, 50);
            pic_AngleSpeed.Click += Pic_AngleSpeed_Click;
        }
        /// <summary>
        /// 扭矩参数设置示意图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Pic_TorqueParams_Click(object sender, EventArgs e)
        {
            pic_ParamSet.Image = Properties.Resources.parameterSet1;
            lblSet1.ForeColor = Color.Blue;
            lblSet2.ForeColor = Color.Black;
            lblSet3.ForeColor = Color.Black;
        }
        /// <summary>
        /// 扭矩范围参数设置示意图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Pic_TorqueRange_Click(object sender, EventArgs e)
        {
            pic_ParamSet.Image = Properties.Resources.parameterSet2;
            lblSet1.ForeColor = Color.Black;
            lblSet2.ForeColor = Color.Blue;
            lblSet3.ForeColor = Color.Black;
        }
        /// <summary>
        /// 速度角度参数设置示意图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Pic_AngleSpeed_Click(object sender, EventArgs e)
        {
            pic_ParamSet.Image = Properties.Resources.parameterSet3;
            lblSet1.ForeColor = Color.Black;
            lblSet2.ForeColor = Color.Black;
            lblSet3.ForeColor = Color.Blue;
        }

        /// <summary>
        /// 获取图片缩略图
        /// </summary>
        /// <param name="originalImage"></param>
        /// <param name="thumbWidth"></param>
        /// <param name="thumbHeight"></param>
        /// <returns></returns>
        public Image GetThumbnail(Image originalImage, int thumbWidth, int thumbHeight)
        {
            //Image originalImage = Image.FromFile(imagePath);
            Image thumbnail = originalImage.GetThumbnailImage(thumbWidth, thumbHeight, () => { return false; }, IntPtr.Zero);
            return thumbnail;
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadParameterData()
        {
            DDKBatch.ReadScrewUpParameters(1);
            ScrewParams = BLL.Bll.GetAllDDKParameter();
            //ScrewParams = new List<ScrewParam>()
            //    {
            //        new ScrewParam()
            //        {
            //            taskId=1,
            //            name="参数1",
            //            tighteningType="扭矩法",
            //            targeAngle=0,
            //            targetTorque=4.5,
            //        },
            //        new ScrewParam()
            //        {
            //            taskId=2,
            //            name="参数2",
            //            tighteningType="角度法",
            //            targeAngle=800,
            //            targetTorque=0,
            //        },
            //        new ScrewParam()
            //        {
            //            taskId=3,
            //            name="参数3",
            //            tighteningType="扭矩法",
            //            targeAngle=0,
            //            targetTorque=5.2,
            //        }
            //    };
            RefreshParamData();
            //默认选择第一个参数
            if (parameterNumGridView.Rows.Count > 0)
            {
                parameterNumGridView.Rows[0].Selected = true;
                DataGridViewCellEventArgs dataGridViewCellEventArgs = new DataGridViewCellEventArgs(1, 0);
                parameterNumGridView_CellClick(parameterNumGridView, dataGridViewCellEventArgs);
            }

        }
        /// <summary>
        /// 添加电批参数
        /// </summary>
        /// <param name="param"></param>
        private void AddScrewParameters(ScrewParam param)
        {
            try
            {
                //if (param.targeAngle == 0 && param.targetTorque == 0)
                //{
                //    readParamFlag = false;
                //    this.BeginInvoke(new Action(() =>
                //    {
                //        parameterNumGridView.Rows.Clear();
                //        foreach(ScrewParam screwParam in ScrewParams)
                //        {
                //            var tempParam = ReadScrewParams.Find(s => s.taskId == screwParam.taskId);
                //            if (tempParam!=null && string.IsNullOrEmpty(tempParam.name))
                //            {
                //                tempParam.name = screwParam.name;
                //            }
                //        }
                //        ScrewParams.Clear();
                //        ScrewParams.AddRange(ReadScrewParams);
                //        //ScrewParams = ReadScrewParams;
                //        RefreshParamData();

                //    }));
                //    return;
                //}
                if (!readParamFlag) return;
                if (string.IsNullOrEmpty(param.name))
                {
                    readParamFlag = false;
                    this.BeginInvoke(new Action(() =>
                    {
                        parameterNumGridView.Rows.Clear();
                        foreach (ScrewParam screwParam in ScrewParams)
                        {
                            var tempParam = ReadScrewParams.Find(s => s.taskId == screwParam.taskId);
                            if (tempParam != null && string.IsNullOrEmpty(tempParam.name))
                            {
                                tempParam.name = screwParam.name;
                            }
                        }
                        ScrewParams.Clear();
                        ScrewParams.AddRange(ReadScrewParams);
                        //ScrewParams = ReadScrewParams;
                        RefreshParamData();

                    }));
                    return;
                }
                ReadScrewParams.Add(param);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"添加电批参数失败->{ex.Message}");
            }

        }

        /// <summary>
        /// 更新参数数据
        /// </summary>
        private void RefreshParamData()
        {
            int index = 0;
            parameterNumGridView.Rows.Clear();
            parameterDataGridView.Rows.Clear();
            ScrewParams.Sort((x, y) => x.taskId.CompareTo(y.taskId));
            foreach (ScrewParam param2 in ScrewParams)
            {
                param2.taskId = param2.taskId;
                parameterNumGridView.Rows.Add();
                parameterNumGridView.Rows[index].Cells["ParamIndexColumn"].Value = param2.taskId;
                parameterNumGridView.Rows[index].Cells["ParamNameColumn"].Value = param2.name;
                parameterNumGridView.Rows[index].Cells["ParamNameColumn"].ToolTipText = $"参数{param2.taskId}";
                index++;
            }
        }

        /// <summary>
        /// 选择参数
        /// </summary>
        private void SelectParam(int index)
        {
            parameterDataGridView.Rows.Clear();
            var param = ScrewParams.Find(o => o.taskId == index);
            if(param!=null)
            {
                (parameterDataGridView.Columns["TighteningTypeColumn"] as DataGridViewComboBoxColumn).DataSource = DDKBatch.TighteningTypeList;
                parameterDataGridView.Rows.Add();
                parameterDataGridView.Rows[0].Cells["TighteningTypeColumn"].Value = param.tighteningType;
                parameterDataGridView.Rows[0].Cells["TargetTorqueColumn"].Value = param.targetTorque;
                parameterDataGridView.Rows[0].Cells["TargetAngleColumn"].Value = param.targeAngle;
                //扭矩法
                if (param.tighteningType ==DDKBatch.TighteningTypeList[0])
                {
                    parameterDataGridView.Columns["TargetTorqueColumn"].Visible = true;
                    parameterDataGridView.Columns["TargetAngleColumn"].Visible = false;
                }
                //角度法
                else if (param.tighteningType == DDKBatch.TighteningTypeList[1])
                {
                    parameterDataGridView.Columns["TargetTorqueColumn"].Visible = false;
                    parameterDataGridView.Columns["TargetAngleColumn"].Visible = true;
                }
                parameterDataGridView.Rows[0].Cells["ReferTorqueColumn"].Value = param.allRangeTorque;
                parameterDataGridView.Rows[0].Cells["MaxTorqueLowLimitColumn"].Value = param.maxTorqueLowLimit;
                parameterDataGridView.Rows[0].Cells["MaxTorqueUpLimitColumn"].Value = param.maxTorqueUpLimit;
                parameterDataGridView.Rows[0].Cells["StartLowSpeedTorqueColumn"].Value = param.slowTorque;
                parameterDataGridView.Rows[0].Cells["FisrtTorqueColumn"].Value = param.firstTorque;
                parameterDataGridView.Rows[0].Cells["SungTorqueColumn"].Value = param.sungTorque;
                parameterDataGridView.Rows[0].Cells["SecondTorqueColumn"].Value = param.secendTorque;
                parameterDataGridView.Rows[0].Cells["StartTimeColumn"].Value = param.startTime;
                parameterDataGridView.Rows[0].Cells["FirstTimeUpLimitColumn"].Value = param.firstTimeUpLimit;
                parameterDataGridView.Rows[0].Cells["SecondTimeUpLimitColumn"].Value = param.secendTimeUpLimit;
                parameterDataGridView.Rows[0].Cells["StartSpeedColumn"].Value = param.startSpeed;
                parameterDataGridView.Rows[0].Cells["NoneSpeedColumn"].Value = param.noTorqueSpeed;
                parameterDataGridView.Rows[0].Cells["FirstSpeedColumn"].Value = param.firstSpeed;
                parameterDataGridView.Rows[0].Cells["SecondSpeedColumn"].Value = param.secendSpeed;
                parameterDataGridView.Rows[0].Cells["ReverseSpeedColumn"].Value = param.reverseSpeed;
                parameterDataGridView.Rows[0].Cells["LastAngleLowlimitColumn"].Value = param.lastAngleLowlimit;
                parameterDataGridView.Rows[0].Cells["LastAngleUplimitColumn"].Value = param.lastAngleUplimit;
            }
        }

        /// <summary>
        /// 更新参数
        /// </summary>
        private void UpdateParamData(int colIndex,int rowIndex)
        {
            int index = (int)parameterNumGridView.Rows[parameterNumGridView.CurrentRow.Index].Cells["ParamIndexColumn"].Value;
            ScrewParam screwParam = ScrewParams.Find(o => o.taskId == index);
            string colName = parameterDataGridView.Columns[colIndex].Name;
            string rowValue= parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value.ToString();
            double value = 0;
            if (colName== "TighteningTypeColumn")
            {
                screwParam.tighteningType = rowValue;

                //扭矩法
                if (rowValue == DDKBatch.TighteningTypeList[0])
                {
                    parameterDataGridView.Columns["TargetTorqueColumn"].Visible = true;
                    parameterDataGridView.Columns["TargetAngleColumn"].Visible = false;
                }
                //角度法
                else if (rowValue == DDKBatch.TighteningTypeList[1])
                {
                    parameterDataGridView.Columns["TargetTorqueColumn"].Visible = false;
                    parameterDataGridView.Columns["TargetAngleColumn"].Visible = true;
                }
                parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = rowValue;
            }
            else if (colName == "TargetTorqueColumn"&&double.TryParse(rowValue,out value))
            {
                if(value> screwParam.allRangeTorque)
                {
                    MessageBox.Show("目标扭矩不能大于校准力矩");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.targetTorque = value;
            }
            else if (colName == "TargetAngleColumn" && double.TryParse(rowValue, out value))
            {
                if (value >= 10000)
                {
                    MessageBox.Show("目标角度不能大于9999.9");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.targeAngle = value;
            }
            else if (colName == "ReferTorqueColumn" && double.TryParse(rowValue, out value))
            {
                if (value >= 100)
                {
                    MessageBox.Show("校准力矩不能大于99");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }    
                screwParam.allRangeTorque = value;
            }
            else if (colName == "MaxTorqueLowLimitColumn" && double.TryParse(rowValue, out value))
            {
                if (value > screwParam.allRangeTorque)
                {
                    MessageBox.Show("最大扭矩下限不能大于校准力矩");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.maxTorqueLowLimit = value;
            }
            else if (colName == "MaxTorqueUpLimitColumn" && double.TryParse(rowValue, out value))
            {
                if (value > screwParam.allRangeTorque)
                {
                    MessageBox.Show("最大扭矩上限不能大于校准力矩");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.maxTorqueUpLimit = value;
            }
            else if (colName == "StartLowSpeedTorqueColumn" && double.TryParse(rowValue, out value))
            {
                if (value >screwParam.targetTorque && screwParam.tighteningType == DDKBatch.TighteningTypeList[0])
                {
                    MessageBox.Show("开始减速扭矩不能大于目标扭矩");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.slowTorque = value;
            }
            else if (colName == "FisrtTorqueColumn" && double.TryParse(rowValue, out value))
            {
                if (value > screwParam.targetTorque && screwParam.tighteningType == DDKBatch.TighteningTypeList[0])
                {
                    MessageBox.Show("1ST扭矩不能大于目标扭矩");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.firstTorque = value;
            }
            else if (colName == "SungTorqueColumn" && double.TryParse(rowValue, out value))
            {
                if (value > screwParam.targetTorque && screwParam.tighteningType == DDKBatch.TighteningTypeList[0])
                {
                    MessageBox.Show("SUNG扭矩不能大于目标扭矩");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.sungTorque = value;
            }
            else if (colName == "SecondTorqueColumn" && double.TryParse(rowValue, out value))
            {
                if (value > screwParam.targetTorque && screwParam.tighteningType == DDKBatch.TighteningTypeList[0])
                {
                    MessageBox.Show("2ND扭矩不能大于目标扭矩");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.secendTorque = value;
            }
            else if (colName == "StartTimeColumn" && double.TryParse(rowValue, out value))
            {
                screwParam.startTime = value;
            }
            else if (colName == "FirstTimeUpLimitColumn" && double.TryParse(rowValue, out value))
            {
                screwParam.firstTimeUpLimit = value;
            }
            else if (colName == "SecondTimeUpLimitColumn" && double.TryParse(rowValue, out value))
            {
                screwParam.secendTimeUpLimit = value;
            }
            else if (colName == "StartSpeedColumn" && double.TryParse(rowValue, out value))
            {
                if (value > 3000)
                {
                    MessageBox.Show("初期速度不能大于3000");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.startSpeed = value;
            }
            else if (colName == "NoneSpeedColumn" && double.TryParse(rowValue, out value))
            {
                if (value > 3000)
                {
                    MessageBox.Show("空转速度不能大于3000");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.noTorqueSpeed = value;
            }
            else if (colName == "FirstSpeedColumn" && double.TryParse(rowValue, out value))
            {
                if (value > 3000)
                {
                    MessageBox.Show("1st速度不能大于3000");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.firstSpeed = value;
            }
            else if (colName == "SecondSpeedColumn" && double.TryParse(rowValue, out value))
            {
                if (value > 3000)
                {
                    MessageBox.Show("2nd速度不能大于3000");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.secendSpeed = value;
            }
            else if (colName == "ReverseSpeedColumn" && double.TryParse(rowValue, out value))
            {
                if (value > 3000)
                {
                    MessageBox.Show("反转速度不能大于3000");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.reverseSpeed = value;
            }
            else if (colName == "LastAngleLowlimitColumn" && double.TryParse(rowValue, out value))
            {
                if (value >= 10000)
                {
                    MessageBox.Show("最終角度下限不能大于9999.9");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.lastAngleLowlimit = value;
            }
            else if (colName == "LastAngleUplimitColumn" && double.TryParse(rowValue, out value))
            {
                if (value >= 10000)
                {
                    MessageBox.Show("最終角度上限不能大于9999.9");
                    parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = oldvalue;
                    return;
                }
                screwParam.lastAngleUplimit = value;
            }

            if (colName != "TighteningTypeColumn")
            {
                parameterDataGridView.Rows[rowIndex].Cells[colIndex].Value = value;
            }
              
        }
        #endregion

        /// <summary>
        /// 切换参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void parameterNumGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if(e.RowIndex==-1)
            {
                return;
            }
            int num = (int)parameterNumGridView.Rows[e.RowIndex].Cells["ParamIndexColumn"].Value;
            var param = ScrewParams.Find(o => o.taskId == num);
            parameterDataGridView.Rows.Clear();
            if (param != null)
            {
                SelectParam(num);
            }
            else
            {
                parameterDataGridView.Rows.Add();
            }


        }

        /// <summary>
        /// 参数表格修改前
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ParameterDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            string newvalue = parameterDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString();
            if (string.IsNullOrEmpty(newvalue)) return;
            if (e.ColumnIndex >0)
            {
                if (!double.TryParse(newvalue, out double value))
                {
                    MessageBox.Show("请输入有效数");
                    parameterDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = oldvalue;
                }
                else
                {
                    if(value<0)
                    {
                        MessageBox.Show("值不能小于0");
                        parameterDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = oldvalue;
                        return;
                    }
                    UpdateParamData(e.ColumnIndex, e.RowIndex);
                }
            }
            else if (e.ColumnIndex == 0)
            {
                if(!string.IsNullOrEmpty(newvalue))
                {
                    UpdateParamData(e.ColumnIndex, e.RowIndex);
                }
            }


        }

        string oldvalue = null;
        /// <summary>
        /// 参数表格修改后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ParameterDataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.RowIndex == -1)
            {
                return;
            }
            oldvalue = parameterDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString();
        }

        /// <summary>
        /// 读参数标志
        /// </summary>
        private bool readParamFlag = false;
        /// <summary>
        /// 读取全部参数
        /// </summary>
        /// <param name="param"></param>
        private void btn_ReadParamDatas_Click(object sender, EventArgs e)
        {
            readParamFlag = true;
            parameterNumGridView.Rows.Clear();
            parameterDataGridView.Rows.Clear();
            ReadScrewParams.Clear();
            Task.Run(() =>
            {
                for (int i = 0; i < 32; i++)
                {
                    if (readParamFlag)
                    {
                        DDKBatch.ReadScrewUpParameters(i + 1);
                        Thread.Sleep(300);
                    }
                }
            });

        }

        /// <summary>
        /// 设置并保存电批参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SetParamDatas_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                BLL.Bll.DeleteAllDDKParameter();
                foreach (ScrewParam param in ScrewParams)
                {
                    BLL.Bll.AddDDKParameterData(param);
                    DDKBatch.WriteScrewUpParameters(param.taskId, param);
                    Thread.Sleep(2000);
                }
                MessageBox.Show("成功设置和保存参数", "设置参数",MessageBoxButtons.OK);
            });

        }
        /// <summary>
        /// 右键菜单，添加参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addParamToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int addIndex =1;
            if(ScrewParams.Count>0)
            {
                addIndex = ScrewParams.Max(o => o.taskId) + 1;
            }
            for (int i=1;i<= ScrewParams.Count;i++)
            {
                if(!ScrewParams.Exists(o => o.taskId == i))
                {
                    addIndex=i; 
                    break;
                }
            }
            ScrewParam screwParam = new ScrewParam();
            screwParam.taskId = addIndex;
            screwParam.name = "新增参数";
            ScrewParams.Add(screwParam);
            RefreshParamData();
        }
        /// <summary>
        /// 右键菜单，删除参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deleteParamToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int index = (int)parameterNumGridView.Rows[parameterNumGridView.CurrentCell.RowIndex].Cells["ParamIndexColumn"].Value;
            ScrewParam screwParam = ScrewParams.Find(o => o.taskId == index);
            if (screwParam != null)
            {
                screwParam.name = "";
                DDKBatch.WriteScrewUpParameters(screwParam.taskId, screwParam);
            }
            ScrewParams.RemoveAll(o=>o.taskId == index);
            RefreshParamData();
        }
        /// <summary>
        /// 导入参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnImportParam_Click(object sender, EventArgs e)
        {
            ScrewParams.Clear();
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Text Files (*.txt)|*.txt";
            openFileDialog.Multiselect = false;//关闭多选
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                using (StreamReader sr = new StreamReader(openFileDialog.FileName))
                {
                    string strLine = sr.ReadLine();
                    while (strLine != null)
                    {
                        string[] paramStrs=strLine.Split(',');
                        if(paramStrs.Length >=27)
                        {

                            ScrewParams.Add(new ScrewParam()
                            {
                                name = paramStrs[0],
                                taskId= int.TryParse(paramStrs[1],out int intValue)? intValue : 0,
                                targetTorque = double.TryParse(paramStrs[2], out double doubleValue) ? doubleValue : 0,
                                targeAngle = double.TryParse(paramStrs[3], out  doubleValue) ? doubleValue : 0,
                                tighteningType = paramStrs[4],
                                allRangeTorque = double.TryParse(paramStrs[5], out  doubleValue) ? doubleValue : 0,
                                maxTorqueLowLimit = double.TryParse(paramStrs[6], out  doubleValue) ? doubleValue : 0,
                                maxTorqueUpLimit = double.TryParse(paramStrs[7], out  doubleValue) ? doubleValue : 0,
                                slowTorque = double.TryParse(paramStrs[8], out  doubleValue) ? doubleValue : 0,
                                firstTorque = double.TryParse(paramStrs[9], out  doubleValue) ? doubleValue : 0,
                                sungTorque = double.TryParse(paramStrs[10], out  doubleValue) ? doubleValue : 0,
                                secendTorque = double.TryParse(paramStrs[11], out doubleValue) ? doubleValue : 0,
                                lastTorqueLowlimit = double.TryParse(paramStrs[12], out doubleValue) ? doubleValue : 0,
                                lastTorqueUplimit = double.TryParse(paramStrs[13], out doubleValue) ? doubleValue : 0,
                                firstAngle = double.TryParse(paramStrs[14], out doubleValue) ? doubleValue : 0,
                                secendAngle = double.TryParse(paramStrs[15], out doubleValue) ? doubleValue : 0,
                                startTime = double.TryParse(paramStrs[16], out doubleValue) ? doubleValue : 0,
                                startSpeed = double.TryParse(paramStrs[17], out doubleValue) ? doubleValue : 0,
                                noTorqueSpeed = double.TryParse(paramStrs[18], out doubleValue) ? doubleValue : 0,
                                firstSpeed = double.TryParse(paramStrs[19], out doubleValue) ? doubleValue : 0,
                                secendSpeed = double.TryParse(paramStrs[20], out doubleValue) ? doubleValue : 0,
                                thirdSpeed = double.TryParse(paramStrs[21], out doubleValue) ? doubleValue : 0,
                                reverseSpeed = double.TryParse(paramStrs[22], out doubleValue) ? doubleValue : 0,
                                firstTimeUpLimit = double.TryParse(paramStrs[23], out doubleValue) ? doubleValue : 0,
                                secendTimeUpLimit = double.TryParse(paramStrs[24], out doubleValue) ? doubleValue : 0,
                                lastAngleLowlimit = double.TryParse(paramStrs[25], out doubleValue) ? doubleValue : 0,
                                lastAngleUplimit = double.TryParse(paramStrs[26], out doubleValue) ? doubleValue : 0
                            });
                        }
                        strLine = sr.ReadLine();
                    }
                    RefreshParamData();
                }
            }

        }
        /// <summary>
        /// 导出参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExportParam_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog=new SaveFileDialog();
            saveFileDialog.Filter = "Text Files (*.txt)|*.txt";
            if (saveFileDialog.ShowDialog()==DialogResult.OK)
            {
                using (StreamWriter sw = new StreamWriter(saveFileDialog.FileName))
                {
                    foreach(var screwParam in ScrewParams)
                    {
                        string paramStr = $"{screwParam.name},{screwParam.taskId},{screwParam.targetTorque},{screwParam.targeAngle},{screwParam.tighteningType},{screwParam.allRangeTorque},{screwParam.maxTorqueLowLimit},{screwParam.maxTorqueUpLimit},{screwParam.slowTorque},{screwParam.firstTorque},{screwParam.sungTorque},{screwParam.secendTorque},{screwParam.lastTorqueLowlimit},{screwParam.lastTorqueUplimit},{screwParam.firstAngle},{screwParam.secendAngle},{screwParam.startTime},{screwParam.startSpeed},{screwParam.noTorqueSpeed},{screwParam.firstSpeed},{screwParam.secendSpeed},{screwParam.thirdSpeed},{screwParam.reverseSpeed},{screwParam.firstTimeUpLimit},{screwParam.secendTimeUpLimit},{screwParam.lastAngleLowlimit},{screwParam.lastAngleUplimit}";
                        sw.WriteLine(paramStr);
                        sw.Flush();
                    }    
                }

            }
        }
    }
}
